<template>
  <div class="container">
    <a-card class="general-card">
      <template #title>
        <div class="page-header">
          <a-space align="center">
            <a-button shape="circle" @click="goBack">
              <template #icon><icon-arrow-left /></template>
            </a-button>
            <h2 style="margin: 0;">收货操作</h2>
          </a-space>
          <div>
            <a-space>
              <a-tag size="medium" color="blue">{{ inboundDetail?.code || '未知单号' }}</a-tag>
              <a-tag size="medium" :color="getInboundStatusColor(inboundDetail?.status)">
                {{ getInboundStatusText(inboundDetail?.status) || '未知状态' }}
              </a-tag>
            </a-space>
          </div>
        </div>
      </template>
      
      <!-- 基础信息区域 -->
      <a-descriptions
        title="基础信息"
        :column="{ xs: 1, sm: 2, md: 3 }"
        :data="basicInfoData || []"
        :bordered="false"
        :loading="dataLoading && !inboundDetail"
        size="large"
      />
      
      
      <!-- 收货操作区域 -->
      <div class="receiving-area">
        <div class="area-title">货物收货信息</div>
        
        <a-table
          :data="detailList"
          :loading="dataLoading"
          :pagination="false"
          :bordered="true"
          row-key="id"
          :rowSelection="rowSelection"
          @selection-change="handleSelectionChange"
        >
          <template #columns>
            <a-table-column title="货物编码" align="center">
              <template #cell="{ record }">{{ record.cargo?.code || '未知' }}</template>
            </a-table-column>
            <a-table-column title="货物名称" align="center">
              <template #cell="{ record }">{{ record.cargo?.name || '未知' }}</template>
            </a-table-column>
            <a-table-column title="规格型号" align="center">
              <template #cell="{ record }">
                <span v-if="record.cargo?.spec && record.cargo?.spec !== '-'">
                  {{ record.cargo?.spec }}
                </span>
                <span v-else style="color: #ccc;">-</span>
              </template>
            </a-table-column>
            <a-table-column title="单位" align="center">
              <template #cell="{ record }">{{ record.cargo?.unit || '个' }}</template>
            </a-table-column>
            <a-table-column title="预期数量" data-index="quantity" align="center" />
            <a-table-column title="实收数量" align="center" :width="150">
              <template #cell="{ record }">
                <a-input-number
                  v-model="record.realQuantity"
                  :min="0"
                  :precision="0"
                  :max="record.quantity"
                  :disabled="record.received || submitting"
                  @change="(value) => handleQuantityChange(record, value)"
                />
              </template>
            </a-table-column>
            <a-table-column title="批次号" align="center" :width="150">
              <template #cell="{ record }">
                <a-input
                  v-model="record.batchNo"
                  placeholder="系统自动生成"
                  :disabled="true"
                  :style="{ color: '#666' }"
                />
              </template>
            </a-table-column>
            <a-table-column title="生产日期" align="center" :width="180">
              <template #cell="{ record }">
                <a-date-picker
                  v-model="record.productionDate"
                  style="width: 100%;"
                  :disabled="record.received || submitting"
                  @change="(date) => validateProductionDate(record, date)"
                />
              </template>
            </a-table-column>
            <a-table-column title="过期日期" align="center" :width="180">
              <template #cell="{ record }">
                <a-date-picker
                  v-model="record.expiryDate"
                  style="width: 100%;"
                  :disabled="record.received || submitting"
                  @change="(date) => validateExpiryDate(record, date)"
                />
              </template>
            </a-table-column>
            <a-table-column title="差异" align="center">
              <template #cell="{ record }">
                <span :class="getVarianceClass(record)">{{ getVariance(record) }}</span>
              </template>
            </a-table-column>
            <a-table-column title="备注" align="center" :width="200">
              <template #cell="{ record }">
                <a-input
                  v-model="record.remark"
                  placeholder="请输入备注"
                  :disabled="record.received || submitting"
                />
              </template>
            </a-table-column>
            <a-table-column title="操作" fixed="right" align="center">
              <template #cell="{ record }">
                <a-space>
                  <a-button
                    v-if="!record.received"
                    type="primary"
                    size="mini"
                    status="success"
                    :disabled="!record.realQuantity || record.realQuantity <= 0 || submitting"
                    @click="handleReceive(record)"
                  >
                    确认收货
                  </a-button>
                  <a-button
                    v-else
                    type="outline"
                    size="mini"
                    disabled
                  >
                    已收货
                  </a-button>
                </a-space>
              </template>
            </a-table-column>
          </template>
        </a-table>
        
        <!-- 表格底部工具栏，按钮统一靠右放置 -->
        <div class="pagination-wrapper">
          <div class="operations-area">
            <a-space>
              <span class="total-count">共 {{ detailList.length }} 条</span>
              <span class="selected-count" v-if="selectedRowKeys.length > 0">
                已选择 {{ selectedRowKeys.length }} 项
              </span>
              <a-button
                type="primary"
                :disabled="!canBatchReceive || submitting"
                @click="handleBatchReceive"
              >
                批量收货
              </a-button>
              <a-button
                type="primary"
                status="success"
                :disabled="!canCompleteReceiving || submitting"
                @click="handleCompleteReceiving"
              >
                完成收货
              </a-button>
            </a-space>
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, reactive, watch, h } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Message, Modal } from '@arco-design/web-vue';
import { useInboundStore } from '@/stores/inbound';
import { IconArrowLeft } from '@arco-design/web-vue/es/icon';
import dayjs from 'dayjs';
import { formatTime } from '@/utils/datetime';
import { formatDate } from '@/utils';

const route = useRoute();
const router = useRouter();
const inboundStore = useInboundStore();

// 从 Store 获取状态映射函数
const { getInboundStatusColor, getInboundStatusText } = inboundStore;

const inboundId = route.params.id;
// 恢复为无类型 ref
const inboundDetail = ref(null); 
const detailList = ref([]); 
const componentLoading = ref(false);
const submitting = ref(false);

// 修改加载状态变量
const dataLoading = ref(false); // 仅数据加载状态

// 表格选择
const selectedRowKeys = ref([]);
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: false,
  checkCrossPage: true,
  onlyCurrent: false,
  getCheckboxProps: (record) => {
    return {
      disabled: record.received,
      label: record.cargo?.name,
    };
  }
});

// 新增：处理表格选择变化的事件处理器
const handleSelectionChange = (keys) => {
  selectedRowKeys.value = keys;
};

// 是否有选中项
const hasSelectedItems = computed(() => {
  return selectedRowKeys.value.length > 0;
});

// 检查入库单状态是否可操作
const isInvalidOrderStatus = computed(() => {
  if (!inboundDetail.value) return true;
  
  // 检查原始状态是否存在，并且是否允许收货
  const originalStatus = inboundDetail.value.original_status;
  const isValid = originalStatus && ['approved', 'receiving'].includes(originalStatus);
  
  return !isValid;
});

// 新增：检查单个商品是否准备好进行批量接收 (移除日志)
const isItemReady = (item) => {
  const isSelected = selectedRowKeys.value.includes(item.id);
  const isQtyAndBatchOk = isReceivable(item) && !!item.batchNo;
  const hasDates = !!item.productionDate && !!item.expiryDate;
  let areDatesValid = false;
  if (hasDates) {
    areDatesValid = dayjs(item.expiryDate).isAfter(dayjs(item.productionDate));
  }
  return isSelected && isQtyAndBatchOk && hasDates && areDatesValid;
};

// 新增：计算是否有任何选中的商品准备好了 (改为：只要有选中即可)
const canBatchReceive = computed(() => hasValidSelectedItems.value);

// 是否可以完成收货
const canCompleteReceiving = computed(() => {
  return detailList.value.every(
    (item) => item.received || item.quantity === 0
  );
});

// 获取差异
const getVariance = (record) => {
  if (!record.realQuantity) {
    return '0';  // 默认为0而不是'-'
  }
  
  const variance = record.realQuantity - record.quantity;
  if (variance === 0) {
    return '无差异';
  }
  
  return variance > 0 ? `+${variance}` : `${variance}`;
};

// 获取差异的样式类
const getVarianceClass = (record) => {
  if (!record.realQuantity) {
    return 'variance-normal';
  }
  
  if (record.realQuantity > record.quantity) {
    return 'variance-positive';
  } else if (record.realQuantity < record.quantity) {
    return 'variance-negative';
  }
  
  return 'variance-normal';
};

// 检查入库单状态是否可操作 (这里可能需要调整逻辑，暂时保留)
const canReceive = computed(() => {
  if (!inboundDetail.value) return false;
  // 只允许状态为1(待收货)的入库单进行收货
  return inboundDetail.value.status === 1;
});

// 重构：直接在 computed 属性中处理基础信息
const basicInfoData = computed(() => {
  if (!inboundDetail.value) {
    // 不打印错误日志，返回空数组
    return [];
  }
  
  const detail = inboundDetail.value;
  
  // 直接处理每个字段的值
  let supplierDisplay = '无';
  if (detail.supplier && detail.supplier.name) {
    supplierDisplay = detail.supplier.name;
  } else if (detail.supplier_name) {
    supplierDisplay = detail.supplier_name;
  } else if (detail.supplier_id !== undefined && detail.supplier_id !== null) {
    supplierDisplay = `ID: ${detail.supplier_id}`;
  }

  let warehouseDisplay = '未知';
  if (detail.warehouse && detail.warehouse.name) {
    warehouseDisplay = detail.warehouse.name;
  } else if (detail.warehouse_name) {
    warehouseDisplay = detail.warehouse_name;
  } else if (detail.warehouse_id !== undefined && detail.warehouse_id !== null) {
    warehouseDisplay = `ID: ${detail.warehouse_id}`;
  }

  let creatorDisplay = '未知';
  if (detail.user && detail.user.nickname) {
    creatorDisplay = detail.user.nickname;
  } else if (detail.creator_name) { // 假设扁平字段是 creator_name
    creatorDisplay = detail.creator_name;
  } else if (detail.user && detail.user.username) {
    creatorDisplay = detail.user.username;
  } else if (detail.user_id !== undefined && detail.user_id !== null) {
    creatorDisplay = `ID: ${detail.user_id}`;
  }

  const data = [
    { label: '入库类型', value: getInboundTypeText(detail.type) || '未知' },
    { label: '供应商', value: supplierDisplay },
    { label: '仓库', value: warehouseDisplay },
    { label: '创建人', value: creatorDisplay },
    { label: '创建时间', value: detail.created_at ? formatTime(detail.created_at) : '-' },
    { label: '备注', value: detail.note || detail.notes || '-' },
  ];
  
  return data;
});

// 新增：入库类型文本转换
const getInboundTypeText = (type) => {
  switch (type) {
    case 1: return '采购入库';
    case 2: return '退货入库';
    case 3: return '调拨入库';
    case 4: return '生产入库';
    case 5: return '其他入库';
    default: return `未知 (${type})`;
  }
};

// 检查单个商品是否准备好进行接收 (核心逻辑)
const isReceivable = (item) => {
  return !item.received && 
         item.realQuantity !== undefined && 
         item.realQuantity !== null && 
         item.realQuantity > 0;
};

// 处理数量变化
const handleQuantityChange = (record, value) => {
  // 确保数量是有效数字
  if (value !== undefined && value !== null) {
    // 确保不超过预期数量
    if (value > record.quantity) {
      value = record.quantity;
      Message.warning(`实收数量已自动调整为预期数量 ${record.quantity}，不能超出预期数量`);
    }
    record.realQuantity = Number(value);
  } else {
    record.realQuantity = 0;
  }
  
  // 自动标记状态
  if (record.realQuantity === 0) {
    record.status = 'exception';
    Message.info('数量为0将被标记为异常商品');
  } else if (record.realQuantity < record.quantity) {
    record.status = 'variance';
    if (record.realQuantity > 0) {
      // Message.info(`商品将标记为部分收货 (${record.realQuantity}/${record.quantity})`); // 移除此处的提示
    }
  } else {
    record.status = 'normal';
  }
};

// 返回上一页
const goBack = () => {
  router.push('/inbound/orders');
};

// 返回上一页
const showStatusInfo = () => {
  const order = inboundDetail.value;
  if (!order) {
    Message.error('未获取到入库单信息');
    return;
  }
  
  // 获取状态的数字和文本表示
  const status = order.status;
  const statusText = getInboundStatusText(status);
  const statusNum = parseInt(String(status));
  
  // 统计商品收货情况
  const totalItems = detailList.value.length;
  const receivedItems = detailList.value.filter(item => item.received).length;
  
  Modal.info({
    title: '入库单状态信息',
    content: `
      <div style="text-align: left">
        <p><strong>入库单号:</strong> ${order.inbound_order_number || order.code || '未知'}</p>
        <p><strong>当前状态:</strong> ${statusText} (${status})</p>
        <p><strong>是否可收货:</strong> ${canReceive.value ? '是' : '否'}</p>
        <p><strong>商品总数:</strong> ${totalItems} 项</p>
        <p><strong>已收货商品:</strong> ${receivedItems} 项</p>
        <p><strong>后端状态码说明:</strong></p>
        <p>1 - 待审核</p>
        <p>2 - 待收货 (允许收货)</p>
        <p>3 - 待上架/收货中 (允许收货)</p>
        <p>4 - 已完成</p>
        <p>5 - 已取消</p>
      </div>
    `,
    okText: '我知道了'
  });
};

// 计算差异 - 添加缺失的函数
const calculateVariance = (expected, actual) => {
  if (actual === undefined || actual === null || expected === undefined || expected === null) {
    return 0;
  }
  return Number(actual) - Number(expected);
};

// 获取入库单详情
const getInboundDetail = async () => {
  try {
    // 仅设置数据加载状态，不影响整个页面结构
    dataLoading.value = true;
    
    // 获取入库单详情
    const dataFromStore = await inboundStore.getInboundDetail(inboundId);
    
    // 修正检查逻辑：检查新变量
    if (!dataFromStore) { 
      throw new Error('获取入库单详情失败：返回数据为空或无效');
    }
    
    // 保存入库单详情 - 使用新变量
    inboundDetail.value = dataFromStore; 
    console.log("Fetched inboundDetail:", inboundDetail.value); // Debug: 确认基础信息数据
    
    // 构建详情列表 - 从新变量中获取 items
    if (dataFromStore.items && Array.isArray(dataFromStore.items)) {
      detailList.value = dataFromStore.items.map(item => {
        const receivedQuantity = item.received_quantity !== undefined ? Number(item.received_quantity) : 0;
        const expectedQuantity = item.quantity !== undefined ? Number(item.quantity) : 0;
        
        // 检查是否完全收货
        const isFullyReceived = receivedQuantity > 0 && receivedQuantity >= expectedQuantity;
        
        // 批次号处理
        const backendBatchNo = item.batch_no || item.batchNo || null;
        
        // 日期处理: 确保从后端获取的日期字符串能被 dayjs 正确解析
        // 后端返回的可能是带时区的完整时间字符串，或只有日期部分
        const parseDate = (dateStr) => {
          if (!dateStr) return null;
          const d = dayjs(dateStr); // dayjs 通常能处理多种格式
          return d.isValid() ? d.format('YYYY-MM-DD') : null; // 格式化为日期选择器需要的格式
        };
        
        const productionDate = parseDate(item.production_date);
        const expiryDate = parseDate(item.expiry_date);

        // 决定是否禁用单行确认按钮: 完全收货
        const disableConfirmButton = isFullyReceived;
        
        // 返回处理后的商品项
        return {
          ...item, // 保留原始 item 的其他属性，如 id, cargo 等
          quantity: expectedQuantity,
          realQuantity: isFullyReceived ? receivedQuantity : expectedQuantity, // 默认使用预期数量
          batchNo: backendBatchNo, // 可能为 null
          productionDate: productionDate, // 格式化后的日期
          expiryDate: expiryDate, // 格式化后的日期
          remark: item.note || '', // 备注
          received: isFullyReceived, // 保留完全收货标志
          disableConfirm: disableConfirmButton, // 按钮禁用状态
        };
      });
      console.log("Processed detailList:", detailList.value); // Debug: 确认列表数据
    } else {
      console.warn('入库单没有商品项或商品项不是数组');
      detailList.value = [];
    }
    
    selectedRowKeys.value = [];
  } catch (error) {
    console.error('获取入库单详情失败:', error);
    // 区分是网络错误还是业务错误（如记录不存在）
    const errorMsg = error?.response?.data?.message || error?.message || '获取入库单详情时发生错误';
    Message.error(errorMsg); 
    // 如果是记录不存在等情况，可能需要跳转回列表
    if (error?.response?.status === 404 || errorMsg.includes('不存在')) {
      // router.push('/inbound/orders');
    }
  } finally {
    // 完成数据加载
    dataLoading.value = false;
  }
};

// 收货处理函数
const handleReceive = async (record) => {
  if (!record.realQuantity || record.realQuantity <= 0) {
    Message.error('请输入有效的实际收货数量');
    return;
  }

  try {
    submitting.value = true; // 使用submitting而不是componentLoading
    
    // 保存原始状态，以便在失败时恢复
    const originalReceivedState = record.received;
    
    // 调用收货API
    const result = await inboundStore.receiveInbound(inboundId, {
      // 明确设置preserveStatus=true，告诉后端不要改变入库单状态
      preserveStatus: true,
      items: [
        {
          order_item_id: record.id,
          received_quantity: record.realQuantity,
          batch_no: record.batchNo || "",
          production_date: record.productionDate,
          expiry_date: record.expiryDate,
          remark: record.remark || ''
        }
      ]
    });
    
    // 操作成功，更新UI状态
    Message.success('收货成功');
    record.received = true;
    
    // 使用setTimeout延迟数据刷新，确保DOM已更新
    setTimeout(async () => {
      try {
        // 静默刷新数据，出错不提示
        await getInboundDetail();
      } catch (refreshError) {
        console.warn('刷新数据失败，但不影响当前操作:', refreshError);
        // 即使刷新失败也不影响当前操作的成功状态
      } finally {
        submitting.value = false;
      }
    }, 500); // 增加延迟时间，确保DOM有足够时间更新
  } catch (error) {
    console.error('收货处理失败:', error);
    Message.error('收货处理失败: ' + (error.message || '未知错误'));
    
    // 操作失败，不改变原始状态
    record.received = false;
    submitting.value = false;
  }
};

// 批量收货按钮的点击处理程序，调用batchReceive方法
const handleBatchReceive = () => {
  batchReceive();
};

// 完成收货处理
const handleCompleteReceiving = async () => {
  if (!canCompleteReceiving.value) {
    Message.warning('尚有未收货的商品，无法完成收货');
    return;
  }
  
  // 检查是否所有项都已处理 (received=true)
  const allReceived = detailList.value.every(item => item.received);
  if (!allReceived) {
    Message.warning('尚有未确认收货的商品，请处理或确认所有项。');
    return;
  }
  
  // 前端引导用户流转到上架页面
  Modal.confirm({
    title: '完成收货确认',
    content: '确认所有商品均已确认收货吗？确认后将更新订单状态为待上架。',
    okText: '确认完成',
    cancelText: '取消',
    okButtonProps: { status: 'success' },
    onOk: async () => {
      try {
        submitting.value = true;
        
        // 先刷新入库单详情，确保获取最新状态
        await getInboundDetail();
        
        // 检查当前状态是否已经是待上架
        if (inboundDetail.value && inboundDetail.value.status === 2) {
          // 已经是待上架状态，直接跳转到上架页面
          Message.success('入库单已处于待上架状态，正在前往上架页面...');
          
          // 保存当前入库单ID用于跳转
          const targetId = inboundId;
          
          setTimeout(() => {
            router.replace(`/inbound/putaway/${targetId}`);
          }, 800);
          submitting.value = false;
          return;
        }
        
        // 如果不是待上架状态，则调用API更新状态
        // 使用数字状态码2(待上架)
        const result = await inboundStore.updateInboundStatus(inboundId, 2);
        
        if (result) {
          // 先显示成功消息，防止页面跳转导致消息无法显示
          Message.success('收货操作完成，订单现在可以进行上架');
          
          // 保存当前入库单ID用于跳转
          const targetId = inboundId;
          
          // 使用setTimeout延迟跳转，给消息显示和DOM更新留出时间
          setTimeout(() => {
            // 使用replace而不是push，防止回退导致问题
            router.replace(`/inbound/putaway/${targetId}`);
          }, 800); // 延长等待时间为800ms，给DOM更多时间完成过渡
        } else {
          Message.error('更新订单状态失败');
          submitting.value = false;
        }
      } catch (error) {
        console.error('完成收货操作异常:', error);
        Message.error('完成收货操作时发生异常');
        submitting.value = false;
      }
    },
    onCancel() {
      // 用户取消，不做任何事
    }
  });
};

// 筛选出有效的已选择项（未收货且实际数量大于0）
const validSelectedItems = computed(() => {
  return selectedRowKeys.value.filter(id => {
    const item = detailList.value.find(item => item.id === id);
    return item && !item.received && item.realQuantity > 0;
  });
});

// 是否有有效的已选择项
const hasValidSelectedItems = computed(() => validSelectedItems.value.length > 0);

// 页面加载时获取数据
onMounted(async () => {
  try {
    await getInboundDetail();
  } catch (error) {
    console.error('页面加载失败:', error);
  }
});

// --- 商品状态映射函数 (保留在本地) ---
// 商品状态色彩
const getProductStatusColor = (record) => {
  switch (record.status) {
    case 'received': return 'green'; // 完全收货
    case 'variance': return 'orange'; // 部分收货/有差异
    case 'exception': return 'red'; // 异常
    case 'pending': return 'blue'; // 待收货
    default: return 'gray'; // 其他未知状态
  }
};

// 商品状态文本
const getProductStatusText = (record) => {
  switch (record.status) {
    case 'received': return '已收货';
    case 'variance': return '部分收货';
    case 'exception': return '异常';
    case 'pending': return '待收货';
    default: return record.status || '未知'; // 显示原始状态或未知
  }
};

// 日期验证函数
const validateProductionDate = (record, date) => {
  if (!date) return;
  
  // 检查是否早于当前日期
  const today = dayjs();
  if (dayjs(date).isAfter(today)) {
    Message.warning('生产日期不能晚于今天');
    record.productionDate = today.format('YYYY-MM-DD');
  }
  
  // 如果已设置了过期日期，确保生产日期早于过期日期
  if (record.expiryDate && dayjs(date).isAfter(dayjs(record.expiryDate))) {
    Message.warning('生产日期必须早于过期日期');
    record.productionDate = dayjs(record.expiryDate).subtract(1, 'day').format('YYYY-MM-DD');
  }
};

// 过期日期验证
const validateExpiryDate = (record, date) => {
  if (!date) return;
  
  // 检查是否晚于生产日期
  if (record.productionDate && dayjs(date).isBefore(dayjs(record.productionDate))) {
    Message.warning('过期日期必须晚于生产日期');
    record.expiryDate = dayjs(record.productionDate).add(1, 'day').format('YYYY-MM-DD');
  }
};

// 批量确认收货
const batchReceive = async () => {
  // 检查入库单状态 - 只支持状态码1(待收货)
  const status = inboundDetail.value?.status;
  const statusNum = parseInt(String(status));
  
  const isValidStatus = statusNum === 1; // 只允许待收货状态
  
  if (!isValidStatus) {
    Message.error(`无法执行批量收货：当前入库单状态为"${getInboundStatusText(status)}"，仅"待收货"状态可以操作`);
    return;
  }

  // 检查是否有有效的选中项
  if (!hasValidSelectedItems.value) {
    Message.warning('请先选择有效的需要批量确认的商品（未收货且数量大于0）');
    return;
  }

  // 验证所有选中的行是否都准备好接收
  const readyItems = [];
  const notReadyItems = [];
  
  for (const key of validSelectedItems.value) {
    const row = detailList.value.find(item => item.id === key);
    if (!row) continue;
    
    // 由于我们使用validSelectedItems，所以这个检查可能多余，但保留为安全检查
    if (row.received) {
      continue;
    }
    
    // 检查日期相关字段
    let missingFields = [];
    
    if (!row.productionDate) {
      missingFields.push('生产日期');
    }
    
    if (!row.expiryDate) {
      missingFields.push('有效期');
    }
    
    // 验证过期日期必须晚于生产日期
    if (row.productionDate && row.expiryDate) {
      const productionDate = dayjs(row.productionDate);
      const expiryDate = dayjs(row.expiryDate);
      
      if (expiryDate.isBefore(productionDate) || expiryDate.isSame(productionDate)) {
        missingFields.push('有效期必须晚于生产日期');
      }
    }
    
    if (missingFields.length > 0) {
      notReadyItems.push(`${row.cargo?.name || '未知货物'}（问题: ${missingFields.join(', ')}）`);
      continue;
    }
    
    // 添加到准备好的列表
    readyItems.push(row);
  }
  
  if (notReadyItems.length > 0) {
    Modal.warning({
      title: '以下商品无法批量确认',
      content: () => h('div', notReadyItems.map(item => h('p', { style: 'margin: 0;' }, item))),
      okText: '我知道了'
    });
    return;
  }
  
  if (readyItems.length === 0) {
    Message.warning('没有符合条件的商品可以批量确认');
    return;
  }
  
  // 确认框
  Modal.confirm({
    title: '批量确认收货',
    content: `确定要批量确认 ${readyItems.length} 个商品的收货吗？操作后将无法撤销。`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        // 只使用submitting状态，避免DOM更新问题
        submitting.value = true;
        
        // 记录原始状态，但不立即修改UI
        const originalStates = readyItems.map(item => ({
          id: item.id,
          received: item.received
        }));
        
        // 构造收货数据
        const items = readyItems.map(row => ({
          order_item_id: row.id,
          received_quantity: Number(row.realQuantity),
          batch_no: row.batchNo || "", // 发送批次号，如果为空则发送空字符串
          production_date: row.productionDate || null,
          expiry_date: row.expiryDate || null,
          remark: row.remark || ''
        }));
        
        // 调用 Store 的 receiveInbound 方法
        const result = await inboundStore.receiveInbound(inboundId, { 
          // 明确设置preserveStatus=true，告诉后端不要改变入库单状态
          preserveStatus: true,
          items 
        });
        
        // 操作成功，更新UI状态
        Message.success(`批量确认收货成功`);
        
        // 更新UI状态为已收货
        for (const key of validSelectedItems.value) {
          const item = detailList.value.find(item => item.id === key);
          if (item) {
            item.received = true;
          }
        }
        
        // 清空选择
        selectedRowKeys.value = [];
        
        // 延迟刷新数据，让消息和DOM更新有时间完成
        setTimeout(async () => {
          try {
            // 刷新整个列表状态
            await getInboundDetail();
            
            // 检查是否所有商品已经收货完成
            const allReceived = detailList.value.every(item => item.received);
            if (allReceived) {
              // 提示用户可以前往上架
              Modal.success({
                title: '收货完成',
                content: '所有商品已收货完成，可以进行上架操作',
                okText: '前往上架',
                okButtonProps: { status: 'success' },
                onOk: () => {
                  // 前往上架页面
                  router.replace(`/inbound/putaway/${inboundId}`);
                }
              });
            }
          } catch (refreshError) {
            console.warn('刷新数据失败，但不影响批量收货操作:', refreshError);
            // 即使刷新失败也不影响当前操作的成功状态
          } finally {  
            submitting.value = false;
          }
        }, 500); // 延长等待时间，确保DOM更新完成
      } catch (error) {
        let errorMsg = '批量收货失败，请重试';
        if (error && error.message) {
          errorMsg = error.message;
        } else if (error && error.response && error.response.data) {
          errorMsg = error.response.data.message || errorMsg;
        }
        Message.error(errorMsg);
        
        // 操作失败，所有商品保持未收货状态
        for (const key of validSelectedItems.value) {
          const item = detailList.value.find(item => item.id === key);
          if (item) {
            item.received = false;
          }
        }
        
        submitting.value = false;
      }
    }
  });
};
</script>

<style scoped>
.container {
  padding: 16px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.general-card {
  margin-bottom: 16px;
  background-color: var(--color-bg-2);
  border-radius: 4px;
  position: relative; /* 添加相对定位，使蒙层可以相对此元素绝对定位 */
}

.receiving-area {
  margin-top: 16px;
}

.area-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-1);
  margin-bottom: 12px;
  position: relative;
  padding-left: 12px;
  line-height: 22px;
}

.area-title::before {
  content: '';
  width: 3px;
  height: 16px;
  background-color: var(--color-primary);
  position: absolute;
  left: 0;
  top: 3px;
}

/* 差异标签样式 */
.variance-normal {
  color: #18a058;
}

.variance-positive {
  color: #ff9800;
}

.variance-negative {
  color: #f53f3f;
}

/* 库位选择器点击样式 */
.location-cell-clickable {
  color: var(--color-link);
  cursor: pointer;
}

.location-cell-clickable.disabled-click {
  color: var(--color-text-3);
  cursor: not-allowed;
}

/* 待上架数量样式 */
.pending-zero {
  color: #86909c;
}

.pending-normal {
  color: #165dff;
  font-weight: 500;
}

.pending-partial {
  color: #ff7d00;
  font-weight: 500;
}

/* 标准分页样式 */
.table-pagination-wrap,
.table-footer {
  display: none; /* 隐藏旧样式 */
}

.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.operations-area {
  display: flex;
  align-items: center;
}

.total-count, 
.selected-count {
  color: var(--color-text-3);
  font-size: 14px;
  margin-right: 16px;
}
</style>